const Koa = require('koa');
const app = new Koa();

// 全局错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { message: err.message };
    console.error(`Koa error caught: ${err.message}`);
  }
});

// 引入各个路由模块
const indexRoutes = require('./routes/index');
const userRoutes = require('./routes/user');
const articleRoutes = require('./routes/article');

// 注册路由
app.use(indexRoutes.routes()).use(indexRoutes.allowedMethods());
app.use(userRoutes.routes()).use(userRoutes.allowedMethods());
app.use(articleRoutes.routes()).use(articleRoutes.allowedMethods());

// 404 兜底
app.use(async (ctx, next) => {
  await next();
  if (ctx.status === 404) {
    ctx.body = { message: '接口不存在' };
  }
});

app.listen(3001, () => {
  console.log('Koa server is running on http://localhost:3001');
});